package com.zwy.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Component
public class RedisCommonUtil {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private JedisPool jedisPool;

    /**
     * 设置过期
     * @param dbIndex
     * @param key
     * @param seconds 秒
     */
    public void expire(int dbIndex, String key, Long seconds) {
        try(Jedis jedis = jedisPool.getResource()) {
            jedis.select(dbIndex);
            jedis.expire(key, seconds);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 检查
     * @param dbIndex
     * @param key
     * @return
     */
    public Boolean exists(Integer dbIndex, String key) {
        try(Jedis jedis = jedisPool.getResource()) {
            jedis.select(dbIndex);
            return jedis.exists(key);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 删除
     * @return
     */
    public boolean del(Integer dbIndex, String key) {
        try(Jedis jedis = jedisPool.getResource()) {
            jedis.select(dbIndex);
            return jedis.del(key) == 1;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
    }
}
